/** 授权功能 */

// 授权缓存
const authorCache = {
  // xxx: {
    // recordAuthorized = false 是否已授权 
    //getRecordAuthorizeFlag = false; 是否被拒绝过
  // }
}


export const SCOPE_RECORD = "scope.record";
export const SCOPE_USERLOCATION = "scope.userLocation";
const SCOPE_RECORD_NAMES = {
  [SCOPE_RECORD]: '麦克风',
  [SCOPE_USERLOCATION]: '定位功能',
}
export const authorizationBehavior = Behavior({
  methods: {
    // 授权
    getRecordAuthorize(name) {
      authorCache[name] = authorCache[name] || {}
      const cache = authorCache[name]
      const scopeName = SCOPE_RECORD_NAMES[name]
      if (cache.recordAuthorized) return Promise.resolve();

      return new Promise((resolve, reject) => {
        wx.getSetting({
          success: function (res) {
            if (!res[name]) {
              //没授权
              wx.authorize({
                scope: name,
                success() {
                  cache.recordAuthorized = true;
                  resolve();
                },
                // 拒绝授权时，则进入手机设置页面，可进行授权设置
                fail() {
                  if (cache.getRecordAuthorizeFlag) {
                    wx.showModal({
                      title: `授权使用${scopeName}`,
                      content: `授权方法：点击页面右上角“...”，点击“设置”，授权“${scopeName}”`,
                      confirmText: "去授权",
                      cancelText: "取消",
                      success: function (res) {
                        //点击“确认”时打开设置页面
                        if (res.confirm) {
                          wx.openSetting({
                            success: (res) => {
                              if (res.authSetting[name]) {
                                cache.recordAuthorized = true;
                                resolve();
                              }
                            },
                          });
                        }
                      },
                    });
                  } else {
                    cache.getRecordAuthorizeFlag = true;
                  }
                },
              });
            } else {
              cache.recordAuthorized = true;
              resolve();
            }
          },
        });
      });
    },
  },
});
